﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AlgorithmCenter
{
    public class AlgorithmCenter200108
    {
        /// <summary>
        /// https://leetcode-cn.com/problems/string-to-integer-atoi/submissions/
        /// 1.越界
        /// 2.开头空格
        /// 3.开头+-号
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int MyAtoi(string str)
        {
            int res = 0;
            bool power = true;
            string resStr = "";
            str = str.TrimStart(' ');

            if (string.IsNullOrEmpty(str))
                return 0;
            if (str[0] == '-')
                power = false;
            if (str[0] == '-' || str[0] == '+')
                str = str.Remove(0, 1);
            if (string.IsNullOrEmpty(str) || !char.IsDigit(str[0]))
                return 0;
            
            foreach (char c in str)
            {
                if (char.IsNumber(c))
                {
                    resStr += c;
                }
                else
                {
                    break;
                }
            }
            try
            {
                if (!power)
                    res = int.MinValue >= -Convert.ToInt64(resStr) ? int.MinValue : -Convert.ToInt32(resStr);
                else
                    res = int.MaxValue < Convert.ToInt64(resStr) ? int.MaxValue : Convert.ToInt32(resStr);
            }
            catch (OverflowException ex)
            {
                return power ? int.MaxValue : int.MinValue;
            }
            return res;
        }
    }
}
